package com.weixt.serial;

/**
 * @Author 祝雨田
 * @Date 2020-07-02 3:52 下午
 * @Function
 */
import java.io.UnsupportedEncodingException;

/**
 * @author shenyutian
 * @data 2020/6/28 5:23 PM
 * 功能
 */
class SerialHexUtils {

    /**
     * 设置班播机声音大小
     * @param macId 班播机id
     * @param sound 声音大小 0-5
     * @return 发送的串口通信内容
     */
    public static byte[] getSerialPortSetting(String macId, int sound) throws NumberFormatException {

        if (macId.length() != 8) {
            throw new NumberFormatException("macId 长度不对");
        }

        if (sound < 0 || sound > 5) {
            throw new NumberFormatException("声音设置不正确");
        }

        byte[] setting = new byte[11];

        setting[0] = (byte) 0xEC;
        setting[1] = (byte) 0xEC;
        setting[2] = (byte) 0x01;
        setting[3] = (byte) 0x06;

        int j = 4;
        for (int i = 0; i < macId.length(); i+=2) {
            setting[j] = (byte) Integer.parseInt(macId.substring(i, i+2));
            j++;
        }

        setting[8] = (byte) 0x01;
        setting[9] = (byte) 0x00;
        setting[10] = (byte) 0x0A;
        return setting;
    }

    /**
     * 设置班播机发送的内容
     * @param macId id
     * @param content 中文内容
     * @return 字节码
     */
    public static byte[] getSerialPortContent(String macId, String content) {

        if (macId.length() != 8) {
            throw new NumberFormatException("macId 长度不对");
        }

        if (content.length() > 8) {
            throw new NumberFormatException("声音播报不正确");
        }

        byte[] bytes = new byte[25];
        bytes[0] = (byte)0xEC;
        bytes[1] = (byte)0xEC;
        bytes[2] = (byte)0x1F;
        bytes[3] = (byte)0x14;

        int j = 4;
        for (int i = 0; i < macId.length(); i+=2) {
            bytes[j] = (byte) Integer.parseInt(macId.substring(i, i+2));
            j++;
        }

        try {
            byte[] gbks = content.getBytes("gbk");
            for (byte gbk : gbks) {
                bytes[j] = gbk;
                j++;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        bytes[24] = (byte) 0x0A;

        return bytes;
    }

    /**
     * 字节数组转16进制
     * @param bytes 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex + ", ");
        }
        return sb.toString();
    }

}

